package com.dispacher.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dispacher.springsupport.SpringSwitch;

public abstract class PropertiesUtil {
	private static Map<Class, List<Field>> fieldsCache = new HashMap<Class, List<Field>>();

	public static void initSpringField(Object instance) {
		List<Field> cacheFields = getCachedFields(instance.getClass());
		if (cacheFields.size() > 0) {
			for (Field field : cacheFields) {
				int mod = field.getModifiers();
				if (mod == 10 || mod == 9) {
					continue;
				}
				Object bean = SpringSwitch.getBean(field.getName());
				if (bean != null) {
					try {
						field.setAccessible(true);
						field.set(instance, bean);
						field.setAccessible(false);
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public static List<Field> getCachedFields(Class cla) {
		List<Field> cacheFields = fieldsCache.get(cla);
		if (cacheFields == null) {
			Field[] fields = cla.getDeclaredFields();
			cacheFields = Arrays.asList(fields);
			fieldsCache.put(cla, cacheFields);
		}
		return cacheFields;
	}
}
